from socket import *
from select import select

HOST = "0.0.0.0"
PORT = 8888
ADDR =(HOST,PORT)

# 监控列表
rlist = []
wlsit = []
xlist = []

def create_socket():
    #创建监听套接字
    sock = socket()
    sock.bind(ADDR)
    # 配合非阻塞IO防止网络中断带来的内部阻塞
    sock.setblocking(False)#设置为非阻塞IO
    return sock

def connect_client(sock):
    # 监听套接字读事件处理
    conn, addr = sock.accept()
    print("Connect from", addr)
    conn.setblocking(False)
    rlist.append(conn) #增加关注对象


def handle(conn):
    # 连接套接字读事件处理
    data = conn.recv(1024)
    if not data:
        rlist.remove(conn)
        conn.close()
        return
    print(data.decode())
    conn.send(b"OK")

def main():
        sock = create_socket()
        sock.listen(5)
        rlist.append(sock) #初始监控的IO对象
        while True:
            try:
                rs, ws, xs = select(rlist, wlsit, xlist)
                for r in rs:
                    if r is sock:
                        connect_client(sock)
                    else:
                        handle(r)
            except KeyboardInterrupt:
                break

if __name__ == '__main__':
    main()